#ifndef __EVENT_H__
#define __EVENT_H__

#define CONN_POOL_SIZE 4096
#define EPOLL_EVENT 512
#define MAX_CONN 10240

/* Now, only support 1K bytes header */
#define MAX_REQUEST_BUF_LEN 1024

typedef void (*event_handler_pt)(struct Event *ev);
typedef long (*time_event_handler_pt)(struct Server *server, long id, void *clientData);

typedef struct Event {
    void            *data;          /* the connection that the event belongs */
    unsigned         write:1;       /* indicate the type of event */
    unsigned         accept:1;      /* indicate the listen socket */
    unsigned         instance:1;    /* to solve the stale event issue */
    unsigned         active:1;      /* indicate if the event is monitored by epoll */
    unsigned         ready:1;       /* indicate if the event can write or read */
    unsigned         closed:1;      /* indicate if the event is closed */
    unsigned         timedout:1;    /* indicate if the event is timeout */
    event_handler_pt  handler;
}Event;

/* 
    Here I use the data structure from redis which is Inefficient
    Todo: Use the mini-heap or rbtree instead
*/
typedef struct TimeEvent {
    long id;                        /* Timer event ID */
    long when_sec;                  /* expire time */
    long when_ms;
    time_event_handler_pt timeProc; /* callback when expired */
    void *clientData;
    struct TimeEvent *next;
} TimeEvent;

#define EVENT_OK 0
#define EVENT_ERROR -1

#define EVENT_READ_EVENT     EPOLLIN
#define EVENT_WRITE_EVENT    EPOLLOUT

#define EVENT_LEVEL_EVENT    0
#define EVENT_CLEAR_EVENT    EPOLLET

#define EVENT_TIME_EVENTS 1
#define EVENT_FILE_EVENT 2
#define EVENT_NOWAIT 4

int EVENT_Init(struct Server *server);
int EVENT_Process_Events(int flags);
int EVENT_Handle_Add_Connection(struct Conn *c);
int EVENT_Handle_Read_Event(Event *rev, int flag);
int EVENT_Handle_Write_Event(Event *wev, int flag);

#endif
